import os
from markitdown import MarkItDown


def convert_pdfs_to_markdown(directory):
    # 创建MarkItDown对象
    markitdown = MarkItDown()

    # 检查目录是否存在
    if not os.path.isdir(directory):
        print(f"错误：目录 {directory} 不存在。")
        return

    # 遍历目录中的所有文件
    for filename in os.listdir(directory):
        if filename.endswith(".pdf"):
            pdf_path = os.path.join(directory, filename)
            markdown_filename = os.path.splitext(filename)[0] + ".md"
            markdown_path = os.path.join(directory, markdown_filename)

            # 打印操作提示
            print(f"正在转换文件：{pdf_path}")
            print(f"Markdown文件将保存为：{markdown_path}")

            # 使用markitdown转换PDF到Markdown
            try:
                result = markitdown.convert(pdf_path)
                with open(markdown_path, 'w', encoding='utf-8') as md_file:
                    md_file.write(result.text_content)
                print(f"转换成功：{markdown_path}")
            except Exception as e:
                print(f"转换失败：{e}")

    print("所有PDF文件转换完成。")


# 用户输入PDF文件目录
pdf_directory = input("请输入PDF文件所在的目录：")
convert_pdfs_to_markdown(pdf_directory)